var id = "";
var treeData = {};
var rowIndex= "%^%%%%";
var page = "";
var index = "";
var rowData = {};
$(document).ready(function() {
	resizeIframeHight();
	fnResize();
	setting.async = async;
	$.fn.zTree.init($("#roletree"), setting);
	delete(setting.async);
	$.ajax({
        type: "POST",
        url:pathUrl("roles/getRole2User.action"),
        success: function(data) {
//        	console.log(data)
        	treeData = data;
        	$.fn.zTree.init($("#usertree"), setting,treeData);
        	var treeObj = $.fn.zTree.getZTreeObj("usertree"); 
        	treeObj.expandAll(true); 
        },
        error: function(request) {
        	swal_Tips_Error();
        }
    });
	change();
	initTable();
});
var async = {
		enable : true,
		url : pathUrl("menu/getjsdqxList.action"),
		type : "POST",
		dataFilter : filter
};
var async1 = {
		enable : true,
		url : pathUrl("roles/getRole2User.action"),
		type : "POST",
		dataFilter : filter
};
var setting = {
		/*async : {
			enable : true,
			url : pathUrl("menu/getjsdqxList.action"),
			type : "POST",
			dataFilter : filter
		},*/
		check: {  
            enable: true,  
            nocheckInherit: false  
        },
		data : {
			/*
			 * keep: { parent:true, leaf:true },
			 */
			simpleData : {
				enable : true,
			}
		},
		callback : {
//			onAsyncSuccess : zTreeOnAsyncSuccess,
//			onClick : onClick
		}
	};

/*
 * @Description: 对返回的json数据进行处理
 * @param : treeId	对应zTree的treeId
 * @param : parentNode	进行异步加载的父节点 JSON 数据对象
 * @param : childNodes	异步加载获取到的数据
 */
function filter(treeId, parentNode, childNodes) {
//	console.log(childNodes);
	if (!childNodes) return null;
	for (var i=0, l=childNodes.length; i<l; i++) {
		childNodes[i].open = "true";
	}
	return childNodes;
}

/*
 * @Description: 初始化表
 * @param : 
 */
function initTable(){
	$('#Role').bootstrapTable('destroy').bootstrapTable({
		url :pathUrl("roles/getRolesList.action"),//请求后台的URL
//		height : 522,//行高
		method : "POST",//请求方式
		//striped : true,//是否显示行间隔色
		cache : false,//是否使用缓存，默认为true
		pagination : true,//是否显示分页
		pageNumber : 1,//初始化加载第几页
		pageSize : 10,//每页的记录行数
		sidePagination : "server", // 分页方式：client客户端分页，server服务端分页
		pageList : [ 10, 25, 50, 100, 'All'],//可供选择的每页的行数
		queryParams : function(params){//传递参数
			var data = {};
			data.offset = params.offset;
			data.row = params.limit;
			data.rName = $("#cxjs").val();
			//data.sortOrder = params.order;//排序
			//data.sortName = params.sort;//排序
			return data;
		},
		rowStyle:'rowStyle',//自定义样式
		dataType : 'JSON',//数据类型
		uniqueId : "rId",//每一行的唯一标识，一般为主键列
		columns : [
		{
			field : "rName",
			align : 'center',
			valign: 'middle',
			width : 200,
			title : '角色',
		},{
			field : 'operate',//如需导出execl field必填operate，否则操作行会被导出
			align : 'center',
			valign: 'middle',
			formatter:operate,
			events: operateEvents,
			title : '操作'
		}],
		onClickRow: function (row,$element) {//行单击
//			console.log($element);
			$('.success').removeClass('success');//去除之前选中的行的，选中样式
			$($element).addClass('success');//添加当前选中的 success样式用于区别
			index = $element.data('index');
			rowIndex = index;
			page = $('.pagination .active').find("a").eq(0).text();
			id = row.rId;
			$("#roleId").val(id);
			$.ajax({
		        type: "POST",
		        url:pathUrl("roles/getRolesList.action"),
		        data : {"rId": id},
		        dataType : "JSON",
		        success: function(data) {
//		        	console.log(data);
		        	roleData = data;
		        	$.fn.zTree.init($("#roletree"), setting, data.menu);
		        	var treeObj = $.fn.zTree.getZTreeObj("roletree"); 
		        	treeObj.expandAll(true);
		        	$.fn.zTree.init($("#usertree"), setting, data.user);
		        	var treeObj = $.fn.zTree.getZTreeObj("usertree"); 
		        	treeObj.expandAll(true);
		        	var data = data.rows[0];
		        	$("#update_rolename").val(data.rName);
		        	$("#modify").iCheck('check'); 
//		        	$("#update_rolename").attr("readonly",true); 
		        	$("#roleModify").show();
		        },
		        error: function(request) {
		        	swal_Tips_Error();
		        }
		    });
		},
		onPageChange : function(number, size){//翻页
			if(page == number){
				rowIndex = index;
			}else{
				$('.success').removeClass('success');
				rowIndex= "%^%%%%";
			}
		},
		onUncheck : function(index){//取消勾选
			$('.success').removeClass('success');
			rowIndex = "%^%%%%";
		}
	});
}

function rowStyle(row, index) {
	var classes = [ 'success' ];
	if (index == rowIndex) {
		return {
			classes : classes[0]
		};
	}
	return {};
}

/*
 * @Description: 还原usertree的初始数据
 * @param : 
 */
function InitialZtree() {
	$.fn.zTree.init($("#usertree"), setting, treeData);
	var treeObj = $.fn.zTree.getZTreeObj("usertree"); 
	treeObj.expandAll(true); 
}
/*
 * 快速查询人员
 */
function lookUp(){
	if($('#username').val()!= ''){
		InitialZtree();//初始化树
		var zTree = $.fn.zTree.getZTreeObj("usertree");
		var nodeList = zTree.getNodesByParamFuzzy("name", $('#username').val());
		//将找到的nodelist节点更新至Ztree内
		$.fn.zTree.init($("#usertree"), setting, nodeList);
	}else{
		InitialZtree();
	}
}
/*
 * 角色查询
 */
function cx(){
	$('#Role').bootstrapTable('refresh');
	$('.success').removeClass('success');
	rowIndex= "%^%%%%";
	$("#update_rolename").val();
	$("#roleId").val("");
	$('#Role').bootstrapTable('refresh');
	$("#roleAdd").iCheck('check'); 
	$("#roleModify").hide();
	var treeObj = $.fn.zTree.getZTreeObj("roletree");
	treeObj.checkAllNodes(false);
	var treeObj1 = $.fn.zTree.getZTreeObj("usertree"); 
	treeObj1.checkAllNodes(false);
}
function operate(value,row,index){
	return '<button type="button" class="btn btn-danger btn-xs deleteRole" >删除</button>';
}

/**
 * 搜索框监听回车事件
 * @param event
 * @returns
 */
$('#cxjs').keypress(function(event) {
	if (event.keyCode === 13) {
		cx();
	}
});

window.operateEvents= {
	'click .deleteRole':function(e, value, row, index){
		showSwal(
			"删除",
			"您确定删除吗？",
			"是的，确定删除",
			function(result){//isConfirm 点击确定按钮，参数true/false
				if(result.value){
					var treeObj = $.fn.zTree.getZTreeObj("usertree");
					var nodes = treeObj.getCheckedNodes(true);
					if(nodes!=0){
					//	swal_Tips("角色已有授权用户,不可删除！");
					//	return false;
					}
					$.ajax({
						type: "POST",
						url:pathUrl("roles/updateRoles.action"),
						data : {"rId":row.rId,"sfyx":"2"},
						dataType : "JSON",
						success: function(data) {
							if(data.code == "0000"){
								swal_Tips_Short(data.message);
								$("#update_rolename").val();
								$("#roleId").val("");
								$('#Role').bootstrapTable('refresh');
								$("#roleAdd").iCheck('check'); 
								$("#roleModify").hide();
								var treeObj = $.fn.zTree.getZTreeObj("roletree");
								treeObj.checkAllNodes(false);
								var treeObj1 = $.fn.zTree.getZTreeObj("usertree"); 
								treeObj1.checkAllNodes(false);
							}else if(data.code == "9999"){
								swal_Tips(data.message);
							}
						},
						error: function(request) {
							swal_Tips_Error();
						}
					});
				}
			}
		)
	}
}
/*
 * @Description: 系统角色授权
 * @param :grantRole()
 */
function grantRole(){
	var val=$('input:radio[name="type"]:checked').val();
	var rId=$("#roleId").val();
	if(val == 1){
		swal_Tips("角色新增中，不能授权！");
		return false;
	}
	if(rId==""){
		swal_Tips("请选择角色进行授权！");
		return false;
	}
	var treeObj = $.fn.zTree.getZTreeObj("usertree");
	var nodes = treeObj.getCheckedNodes(true);
	if(nodes==""){
		swal_Tips("请选择用户进行授权！");
		return false;
	}
	var ids = '';
	for (var i=0, l=nodes.length; i<l; i++) {
		if(ids != ''){
    		ids += ',';
    	}
    	ids += nodes[i].id;
	}
	$.ajax({
        type: "POST",
        url:pathUrl("roles/roleAddNewsUser.action"),
        data : {"rId":rId,"ids":ids},
        dataType : "JSON",
        success: function(data) {
        	if(data.code == "0000"){
        		swal_Tips_Short(data.message);
        		$("#update_rolename").val();
        		$('#Role').bootstrapTable('refresh');
        	}else if(data.code == "9999"){
        		swal_Tips(data.message);
        	}
        },
        error: function(request) {
        	swal_Tips_Error();
        }
    });
}

/*
 * @Description: 单选按钮改变事件
 * @param :
 */
function change() {
	$('input[type=radio][name=type]').on('ifChecked', function(event){
		if (this.value == 1) {
			$("#update_rolename").val("");
			var treeObj = $.fn.zTree.getZTreeObj("roletree"); 
        	treeObj.checkAllNodes(false);
        	var treeObj = $.fn.zTree.getZTreeObj("usertree"); 
        	treeObj.checkAllNodes(false);
			//权限列表置空
		} else if (this.value == 2) {
			$.fn.zTree.init($("#roletree"), setting, roleData.menu);
			var treeObj = $.fn.zTree.getZTreeObj("roletree"); 
        	treeObj.expandAll(true);
        	$.fn.zTree.init($("#usertree"), setting, roleData.user);
        	var treeObj = $.fn.zTree.getZTreeObj("usertree"); 
        	treeObj.expandAll(true);
        	var data = roleData.rows[0];
        	$("#update_rolename").val(data.rName);
		}
//		$("#update_rolename").attr("readonly",false); 
	});
}

/*
 * @Description: 保存
 * @param : 
 */
function updateRoleSave(){
	var treeObj = $.fn.zTree.getZTreeObj("roletree");
	var nodes = treeObj.getCheckedNodes(true);
	var ids = '';
	for (var i=0, l=nodes.length; i<l; i++) {
		if(ids != ''){
    		ids += ',';
    	}
    	ids += nodes[i].id;
	}
	var val=$('input:radio[name="type"]:checked').val();
	if(val == 1){
		//新增角色的方法
		$.ajax({
	        type: "POST",
	        url:pathUrl("roles/addNew.action"),
	        data : {
	        	"rName":$("#update_rolename").val(),
	        	"ids":ids
	        },
	        dataType : "JSON",
	        success: function(data) {
	        	if(data.code == "0000"){
	        		swal_Tips_Short(data.message);
	        		$("#update_rolename").val("");
	        		var treeObj = $.fn.zTree.getZTreeObj("roletree"); 
	            	treeObj.checkAllNodes(false);
	            	var treeObj1 = $.fn.zTree.getZTreeObj("usertree"); 
	            	treeObj1.checkAllNodes(false);
	        		$('#Role').bootstrapTable('refresh');
	        		$('.success').removeClass('success');
					rowIndex= "%^%%%%";
					$("#roleModify").css('display','none');
					$("#roleId").val("");
	        	}else if(data.code == "9999"){
	        		swal_Tips(data.message);
	        	}
	        },
	        error: function(request) {
	        	swal_Tips_Error();
	        }
	    });
		//新增往角色和权限中间表添加数据
		
	}else if(val == 2){
		//修改角色的方法
		$.ajax({
	        type: "POST",
	        url:pathUrl("roles/updateRoles.action"),
	        data : {"rId":id,"rName":$("#update_rolename").val(),"ids":ids},
	        dataType : "JSON",
	        success: function(data) {
	        	if(data.code == "0000"){
	        		swal_Tips_Short(data.message);
	        		$('#Role').bootstrapTable('refresh');
	        	}else if(data.code == "9999"){
	        		swal_Tips(data.message);
	        	}
	        },
	        error: function(request) {
	        	swal_Tips_Error();
	        }
	    });
		//修改角色和权限中间表数据
	}else if(val == undefined){
		swal_Tips("请选择一个操作！");
	}
}
/*
 * @Description: 浏览器窗口大小改变后：
 * 				 class为ztree，divClassLeft，divClassRight的高度随之改变，
 * 				 divClassLeft的最大高度和最小高度随之改变
 * @param :
 */
function fnResize() {
	var height = $(window).height() - 15;//获取浏览器窗口大小
	document.getElementsByClassName("blank_bg")[0].style.height = $(window).height() +"px";
	document.getElementsByClassName("divClassLeft")[0].style.height = height +"px";
	document.getElementsByClassName("divClassLeft")[0].style.maxHeight = height +"px";
	document.getElementsByClassName("divClassLeft")[0].style.minHeight = height +"px";
	document.getElementsByClassName("divClassLeft")[1].style.maxHeight = height +"px";
	document.getElementsByClassName("divClassLeft")[1].style.minHeight = height +"px";
	document.getElementsByClassName("divClassRight")[0].style.maxHeight = height +"px";
	document.getElementsByClassName("divClassRight")[0].style.minHeight = height +"px";
	document.getElementsByClassName("well")[0].style.maxHeight = (height - 80) +"px";
	document.getElementsByClassName("well")[1].style.maxHeight = (height - 80) +"px";
	document.getElementById("roletree").style.height = (height - 80) +"px";
	document.getElementById("usertree").style.height = (height - 80) +"px";
}
/*
 * @Description: 浏览器窗口大小自适应
 * @param :
 */
$(window).resize(function() {
	window.setTimeout(function() {
		fnResize();
	}, 0);
});